package com.gaga.metadata.convert;


import com.gaga.metadata.common.enums.DbOperatorType;
import com.gaga.metadata.common.enums.ModelFilterType;
import com.gaga.metadata.entity.base.BaseFilter;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 对于fliter相关的转换 IFilterConvert
 *
 * @author liujia
 * @since 2021/7/20 14:39
 **/
public abstract class AbstractFilterConvert<T extends BaseFilter> implements IFilterConvert<T> {

    @Override
    public String convertOperatorType(T filter) {
        DbOperatorType dbOperatorType = DbOperatorType.ofCode(filter.getOper());
        if (dbOperatorType == null) {
            return filter.getOper();
        }
        return dbOperatorType.getSqlCode();
    }

    /**
     * 数值转换
     *
     * @return
     */
    @Override
    public String convertFilterValue(T filter) {
        String filterValue = filter.getValue();
        if (StringUtils.isEmpty(filterValue) || filter.getFieldType() == null) {
            return filterValue;
        }
        switch (filter.getFieldType()) {
            case S:
            case DT:
                filterValue = filterValue.startsWith("'") ? filterValue : "'" + filterValue;
                filterValue = filterValue.endsWith("'") ? filterValue : filterValue + "'";
                break;
            case SS:
                List<String> filterList = new ArrayList<>();
                Arrays.stream(filterValue.split(",")).forEach(value -> {
                    value = value.startsWith("'") ? value : "'" + value;
                    value = value.endsWith("'") ? value : value + "'";
                    filterList.add(value);
                });
                filterValue = StringUtils.join(filterList, ",");
                break;
            case N:
            case NS:
                filterValue = filterValue.replace("'", "");
                break;
            default:
                break;
        }
        return filterValue;
    }

    /**
     * 暴露一个对外的filter2个都转换的方法
     *
     * @param filter
     */
    @Override
    public void convertFilterAll(T filter) {
        //操作符转换  比如 ！= 转换为<>
        if (filter != null && filter.getType() != null) {
            if (ModelFilterType.symbol.getCode().equals(filter.getType().getCode())) {
                filter.setOper(convertOperatorType(filter));
            } else if (ModelFilterType.value.getCode().equals(filter.getType().getCode())) {
                filter.setValue(convertFilterValue(filter));
            }
        }
    }

}
